package com.open.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.open.bean.ImageRecognition;
import com.open.bean.RequestRecord;
import com.open.component.JwtComponent;
import com.open.result.OpenResult;
import com.open.service.ImageRecognitionService;
import com.open.util.ImgUtil;
import com.open.util.SystemQueryUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author typsusan
 * <p>des</p>
 **/
@RestController
@RequestMapping("/request/open")
@Slf4j
public class ImageRecognitionController {

    @Autowired
    ImageRecognitionService imageRecognitionService;

    @Autowired
    JwtComponent jwtComponent;

    @PostMapping("/image/recognition")
    public OpenResult recognition(@RequestBody JSONObject jsonObject, HttpServletRequest request){
        if (StrUtil.isBlank(jsonObject.getStr("base64")) || StrUtil.isBlank(jsonObject.getStr("code"))){
            return OpenResult.error("缺少必要的参数");
        }
        if(SystemQueryUtil.isWindows()){
            return OpenResult.success("[[https://plumgpt.com/chat/default/28.jpg]]");
        }
        String wId = jwtComponent.getUserWId(request);
        Integer count = imageRecognitionService.lambdaQuery()
                .eq(ImageRecognition::getWid, wId)
                .last("AND TO_DAYS(create_time) = TO_DAYS(NOW())").count();
        if (count >= 30){
            return OpenResult.error("今日图片上传上限");
        }
        String generateImage = ImgUtil.generateImage(
                jsonObject.getStr("base64").replace("data:image/png;base64,",""),
                ImgUtil.TEXT_IMG_PATH,".png");
        ImageRecognition imageRecognition = new ImageRecognition();
        imageRecognition.setCreateTime(new Date());
        imageRecognition.setMsgCode(jsonObject.getStr("code"));
        imageRecognition.setImg("/data"+generateImage);
        imageRecognition.setWid(Integer.parseInt(wId));
        imageRecognitionService.save(imageRecognition);
        return OpenResult.success("[["+"https://plumgpt.com"+generateImage+"]]");
    }

}
